﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

/*
    Socket1项目，主要弄清楚socket的初始化及怎样发送消息、接受消息
*/
namespace Socket1.Client
{
    class Program
    {
        static void Main(string[] args)
        {
            IPAddress ip = IPAddress.Parse("127.0.0.1");
            IPEndPoint ipe = new IPEndPoint(ip, 5001);
            //1.建立一个Socket对象
            Socket socketClient = new Socket(AddressFamily.InterNetwork,
            SocketType.Stream, ProtocolType.Tcp);
            try
            {
                //2.去连接这个IP(没有Socket监听这个端口，就会报错)
                socketClient.Connect(ipe);
                Console.WriteLine("连接服务端" + ipe + "成功");
                //发送信息给服务端
                string sendMessage = "Hello SocketServer,I am SocketClient.";
                byte[] sendBytes = Encoding.UTF8.GetBytes(sendMessage);
                socketClient.Send(sendBytes);
                //接收信息
                string receiveMessage = "";
                byte[] receiveBytes = new byte[2048];
                //客户端会一直等待服务器发送消息，否则不继续执行
                int byteLen = socketClient.Receive(receiveBytes,
                receiveBytes.Length, 0);
                receiveMessage += Encoding.UTF8.GetString(receiveBytes, 0, byteLen);
                Console.WriteLine("服务器信息：" + receiveMessage);
                //释放Socket占用的资源
                socketClient.Dispose();
                Console.ReadKey();
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}
